package com.team.instantsharing.management

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.security.SignatureException
import java.text.DateFormat
import java.text.DecimalFormat
import java.text.SimpleDateFormat

import com.amazonaws.util.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper

import org.springframework.web.client.RestTemplate;
import org.apache.commons.codec.binary.Base64;
import org.codehaus.groovy.grails.web.json.JSONArray;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.team.instantsharing.dto.Document;
import com.team.instantsharing.dto.DocumentRealtime;
import com.team.instantsharing.dto.File;
import com.team.instantsharing.dto.Folder;
import com.team.instantsharing.dto.FolderInformation;
import com.team.instantsharing.dto.Message;
import com.team.instantsharing.dto.PathDTO;
import com.team.instantsharing.dto.S3Config;
import com.team.instantsharing.ultils.Constant;
import com.team.instantsharing.ultils.FileConvert;
import com.team.instantsharing.ultils.ServiceRequest;

import grails.converters.JSON
import grails.util.Holders;

class ManageController {
	
	def grailsApplication = Holders.getGrailsApplication()
	private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

	def index() {
		if (session.userEmail == null || session.userEmail == ""){
			redirect controller:'home', action: 'index';
			return;
		}
		String path = params.path;
		if (path == null || path == ""){
			path = "";
		}
		String trashStatus = params.trashStatus;
		if (trashStatus == null || trashStatus == ""){
			trashStatus = "false";
		}
		RestTemplate restTemplate = new RestTemplate();
		List<Document> listDocuments = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.GET_LIST_DOCUMENT + "?userEmail=" + session.userEmail + "&path=" + path + "&trashStatus=" + trashStatus, Document[].class);
		
		//Get current folder information
		String realS3Path = "";
		FolderInformation folderInfo = null;
		if (path != ""){
			folderInfo = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.GET_FOLDER_INFORMATION + "?userEmail=" + session.userEmail + "&folderPath=" + path, FolderInformation.class);
			if (folderInfo.getRealPathToFolder() != null && folderInfo.getRealPathToFolder() != ""){
				realS3Path = folderInfo.getRealPathToFolder() + Constant.SUFFIX + folderInfo.getRealNameOfFolder();
			} 
			else{
				realS3Path = folderInfo.getRealNameOfFolder();
			}
			folderInfo.setRealPathToFolder(realS3Path);
		}
		else{
			realS3Path = "";
			folderInfo = new FolderInformation()
			folderInfo.setUserEmailOwner(session.userEmail);
			folderInfo.setRealPathToFolder(realS3Path);
		}
		//End get current folder information
		
		for (Document document in listDocuments) {
			if (document.getDocumentPath() == null || document.getDocumentPath() == ""){
				document.setDocumentPath("");
			}
			else{
				document.setDocumentPath(document.getDocumentPath() + Constant.SUFFIX);
			}
		}
		List<String> breadcrum = new ArrayList<String>();
		if (path.trim().length() > 0){
			breadcrum = (List<String>)path.split(Constant.SUFFIX);
		}
		String[] pathSplit = path.split(Constant.SUFFIX); 
		List<String> pathLink = new ArrayList<String>();
		
		for (int i = pathSplit.length - 1; i>0; i--) {
			String pathTmp = "";
			for(int j=0; j < i; j++) {
				pathTmp += pathSplit[j] + Constant.SUFFIX;
			}
			pathTmp = pathTmp.substring(0, pathTmp.length() - 1);
			pathLink.add(pathTmp);
		}
		pathLink = pathLink.reverse();
		
		//Config for upload file to S3
		String contextPath = grailsApplication.config.my.global.variable.path;
		S3Config s3Config = getS3Config(folderInfo.getUserEmailOwner());
		List<String> listDocumentString = getListDocumentCapacityString(listDocuments);
		List<String> listDocumentExtension = getListDocumentExtension(listDocuments);
		[listDocuments:listDocuments, pathLink:pathLink, breadcrum:breadcrum, currentPath:path, s3Config:s3Config, contextPath:contextPath, realS3Path:realS3Path, folderInfo:folderInfo, listDocumentString:listDocumentString, listDocumentExtension:listDocumentExtension]
	}
	
	private List<String> getListDocumentCapacityString(List<Document> listDocument){
		List<String> listDocumentCapacityString = new ArrayList<String>();
		DecimalFormat df = new DecimalFormat("###.##");
		for (Document document in listDocument) {
			if (document.getDocumentCapacity() >= 1073741824) {
				listDocumentCapacityString.add(df.format(document.getDocumentCapacity() / 1073741824.0) + ' GB');
			}
			else if (document.getDocumentCapacity() >= 1048576) {
				listDocumentCapacityString.add(df.format(document.getDocumentCapacity() / 1048576.0) + ' MB');
			}
			else if (document.getDocumentCapacity() >= 1024) {
				listDocumentCapacityString.add(df.format(document.getDocumentCapacity() / 1024.0) + ' KB');
			}
			else {
				listDocumentCapacityString.add(document.getDocumentCapacity() + ' B');
			}
		}
		return listDocumentCapacityString;
	}
	
	private List<String> getListDocumentExtension(List<Document> listDocument){
		List<String> listDocumentExtension = new ArrayList<String>();
		for (Document document in listDocument) {
			String documentName = document.getDocumentName();
			if (documentName.contains(".")){
				String extn = documentName.substring(documentName.lastIndexOf('.') + 1, documentName.length());
				extn = extn.toLowerCase();
				switch (extn){
					case "png": extn="PNG Image"; break;
					case "jpg": extn="JPEG Image"; break;
					case "svg": extn="SVG Image"; break;
					case "gif": extn="GIF Image"; break;
					case "ico": extn="Windows Icon"; break;
					
					case "txt": extn="Text File"; break;
					case "log": extn="Log File"; break;
					case "htm": extn="HTML File"; break;
					case "php": extn="PHP Script"; break;
					case "js": extn="Javascript"; break;
					case "css": extn="Stylesheet"; break;
					case "pdf": extn="PDF Document"; break;
					
					case "mp3": extn="MP3 Music"; break;
					case "mp4": extn="MP4 Video"; break;					
					case "avi": extn="AVI Video"; break;
					
					case "zip": extn="ZIP Archive"; break;
					case "bak": extn="Backup File"; break;
					
					case "ppt": 
					case "pptx": extn="PowerPoint File"; break;
					case "doc": 
					case "docx": extn="Word File"; break;
					case "xls": 
					case "xlsx": extn="Excel File"; break;
					
					default: extn = "File"; break;
				}
				listDocumentExtension.add(extn);
			}
			else{
				listDocumentExtension.add("");
			}
		}
		return listDocumentExtension;
	}
	
	public static String generateHMAC(String data, String secretKey)throws java.security.SignatureException {
		String resultSigningKey = null;
		try {
			SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(),HMAC_SHA1_ALGORITHM);
			Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(data.getBytes());
			resultSigningKey = new String(Base64.encodeBase64(rawHmac));
		} catch (Exception e) {
			throw new SignatureException("Failed to generate HMAC : "+ e.getMessage());
		}
		return resultSigningKey;
	}
	
	private S3Config getS3Config(String folderEmail){
		String bucketS3 = grailsApplication.config.grails.plugin.awssdk.s3Bucket;
		String accessKeyId = grailsApplication.config.grails.plugin.awssdk.accessKey;
		String secretKey = grailsApplication.config.grails.plugin.awssdk.secretKey;
		String aclPermission = "public-read";
		String successStatus = "201";
		String policyS3 = null;
		String base64Policy = null;
		String signature = null;
		String key = "\$"+"key";
		String rootPath = folderEmail + "/";
		
		JSONObject bucket = new JSONObject();
		bucket.put("bucket", bucketS3);

		JSONObject acl = new JSONObject();
		acl.put("acl", aclPermission);
		
		JSONObject status = new JSONObject();
		status.put("success_action_status", successStatus);

		JSONArray pathFolderandFile = new JSONArray();
		pathFolderandFile.add("starts-with");
		pathFolderandFile.add(key);
		pathFolderandFile.add(rootPath);

		JSONArray conditions = new JSONArray();
		conditions.add(bucket);
		conditions.add(acl);
		conditions.add(status);
		conditions.add(pathFolderandFile);

		DateTime output = new DateTime(DateTimeZone.UTC);
		
		output = output.plusHours(6);
		
		JSONObject objPolicy = new JSONObject();
		objPolicy.put("expiration", output.toString());
		objPolicy.put("conditions", conditions);
		
		byte[] bytesEncoded = Base64.encodeBase64(objPolicy.toString().getBytes());

		base64Policy = new String(bytesEncoded);
		
		try {
			signature = generateHMAC(base64Policy,secretKey);
		} catch (SignatureException e) {
			e.printStackTrace();
		}
		
		S3Config s3Config = new S3Config();
		s3Config.setS3Bucket(bucketS3);
		s3Config.setAccessKeyId(accessKeyId);
		s3Config.setSecretKey(secretKey);
		s3Config.setAclPermission(aclPermission);
		s3Config.setBase64Policy(base64Policy);
		s3Config.setSignature(signature);
		s3Config.setRootPath(rootPath);
		
		return s3Config;
	}
	
	def trash(){
		if (session.userEmail == null || session.userEmail == ""){
			redirect controller:'home', action: 'index';
			return;
		}
		RestTemplate restTemplate = new RestTemplate();
		List<Document> listDocuments = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.GET_LIST_DOCUMENT_IN_TRASH + "?userEmail=" + session.userEmail + "&trashStatus=true", Document[].class);
		List<String> listDocumentExtension = getListDocumentExtension(listDocuments);
		[listDocuments:listDocuments, listDocumentExtension:listDocumentExtension]
	}
	def moveDocumentToTrash(){
		println params.documentType + "-" + params.documentName + "-" + params.documentRealPath + "-" + params.documentEmail;
		Integer documentType = Integer.parseInt(params.documentType);
		String documentName = params.documentName;
		String documentPath = params.documentRealPath;
		String documentEmail = params.documentEmail;
		
		Message message; 
		if (documentType == Constant.DOC_FOLDER){
			Folder folder = new Folder();
			folder.setFolderName(documentName);
			folder.setFolderPath(documentPath);
			folder.setUserEmail(documentEmail);
			
			RestTemplate restTemplate = new RestTemplate();
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.MOVE_FOLDER_TO_TRASH, folder, Message.class);
		}
		else if (documentType == Constant.DOC_FILE){
			File file = new File();
			file.setFileName(documentName);
			file.setFilePath(documentPath);
			file.setUserEmail(documentEmail);
			
			RestTemplate restTemplate = new RestTemplate();
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.MOVE_FILE_TO_TRASH, file, Message.class);
		}
		else{
			message = new Message("Document Type Error");
		}
		render ([info:message.response] as JSON)
	}

	
	def photoManage(){
		redirect controller:'photo', action: 'gallery';
	}
	

	def restoreDocument(){
		String documentName = params.documentName;
		Integer documentType = Integer.parseInt(params.documentType);
		String documentPath = params.documentPath;
		String userEmail = params.userEmailOwner;
		
		println documentName + documentType + documentPath + userEmail
		
		Message message;
		if (documentType == Constant.DOC_FOLDER){
			Folder folder = new Folder();
			folder.setFolderName(documentName);
			folder.setFolderPath(documentPath);
			folder.setUserEmail(userEmail);
			
			RestTemplate restTemplate = new RestTemplate();
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.RESTORE_FOLDER_FROM_TRASH, folder, Message.class);
		}
		else if (documentType == Constant.DOC_FILE){
			File file = new File();
			file.setFileName(documentName);
			file.setFilePath(documentPath);
			file.setUserEmail(userEmail);
			
			RestTemplate restTemplate = new RestTemplate();
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.RESTORE_FILE_FROM_TRASH, file, Message.class);
		}
		else{
			message = new Message("Document Type Error");
		}
		render ([info:message.response] as JSON)
	}
	def restoreDocumentWithFolderParent(){
		String documentName = params.documentName;
		Integer documentType = Integer.parseInt(params.documentType);
		String documentPath = params.documentPath;
		String userEmail = session.userEmail;
		documentPath = (documentPath == "")? null : documentPath.substring(0, documentPath.length() - 1);
		Message message;
		if (documentType == Constant.DOC_FOLDER){
			Folder folder = new Folder();
			folder.setFolderName(documentName);
			folder.setFolderPath(documentPath);
			folder.setUserEmail(userEmail);
			
			RestTemplate restTemplate = new RestTemplate();
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.RESTORE_FOLDER_WITH_FOLDER_PARENT, folder, Message.class);
		}
		else{
			println "File";
		}
		render ([info:message.response] as JSON)
	}
	def deletePermanentlyDocument(){
		Integer documentType = Integer.parseInt(params.documentType);
		String documentName = params.documentName;
		String documentPath = params.documentPath;
		String documentEmail = params.documentEmail;
		Message message;
		if (documentType == Constant.DOC_FOLDER){
			Folder folder = new Folder();
			folder.setFolderName(documentName);
			folder.setFolderPath(documentPath);
			folder.setUserEmail(documentEmail);
			RestTemplate restTemplate = new RestTemplate();
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.DELETE_FOLDER, folder, Message.class);
		}
		else{
			File file = new File();
			file.setFileName(documentName);
			file.setFilePath(documentPath);
			file.setUserEmail(documentEmail);
			RestTemplate restTemplate = new RestTemplate();
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.DELETE_FILE, file, Message.class);
		}
		
		RestTemplate restTemplate = new RestTemplate();
		Message capacityMessage = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.GET_CAPACITY + "?userEmail=" + session.userEmail, Message.class);
		session.usedCapacity = Long.parseLong(capacityMessage.response);
		session.usedCapacityString = FileConvert.getDocumentCapacityString(session.usedCapacity);
		Long percent = (int)(session.usedCapacity * 100 / session.availableCapacity);
		
		render ([info:message.response, usedCapacity:session.usedCapacityString, avaiCapacity:session.availableCapacityString, percent: percent] as JSON)
	}

	def search(){
		String searchQuery = params.searchContent;
		List<Document> listDocuments = new ArrayList<Document>();
		List<String> listDocumentString = new ArrayList<String>();
		List<String> listDocumentExtension = new ArrayList<String>();
		if (searchQuery.length() > 0){
			RestTemplate restTemplate = new RestTemplate();
			listDocuments = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.SEARCH_DOCUMENT + "?userEmail=" + session.userEmail + "&searchQuery=" + searchQuery, Document[].class);
			listDocumentString = getListDocumentCapacityString(listDocuments);
			listDocumentExtension = getListDocumentExtension(listDocuments);
		}
		[listDocuments:listDocuments, listDocumentString:listDocumentString, listDocumentExtension:listDocumentExtension, searchQuery:searchQuery]
	}
	
	def realTimeUpdateData(){
		String currentPath = params.currentPath;
		String trashStatus = params.trashStatus;
		String userEmail = params.userEmailOwner;
		String listDocumentOld = params.listDocumentOld;
//		println listDocumentOld
		List<Document> listDocumentFromJSON = null;
		if (listDocumentOld != null && !listDocumentOld.equals("Success")){
			listDocumentFromJSON = parseListDocumentFromJson(listDocumentOld);
		}
		RestTemplate restTemplate = new RestTemplate();

		List<Document> listDocuments = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.GET_LIST_DOCUMENT + "?userEmail=" + userEmail + "&path=" + currentPath + "&trashStatus=" + trashStatus, Document[].class);
		
		boolean checkSameList = true;
		if (listDocumentFromJSON != null){
			if (listDocumentFromJSON.size() == listDocuments.size()){
				for (int i=0; i < listDocumentFromJSON.size(); i++) {
					if (!compareDocument(listDocumentFromJSON.get(i), listDocuments.get(i))){
						println "Not Same";
						checkSameList = false;
						break;
					}
				}
			}
			else{
				checkSameList = false;
			}
		}
		
		if (checkSameList){
			render ([info:"Success"] as JSON)
		}
		else{
			List<DocumentRealtime> listDocumentRealtimes = convertDocumentToDocumentRealtime(listDocuments);
			Collections.reverse(listDocumentRealtimes);
			String[][] dataForDataTable = new String[listDocuments.size()];
			for(int i = 0; i < listDocuments.size(); i++){
				dataForDataTable[i] = new String[8];
				dataForDataTable[i][0] = listDocumentRealtimes.get(i).getDocumentName();
				dataForDataTable[i][1] = listDocumentRealtimes.get(i).getDocumentKind();
				dataForDataTable[i][2] = listDocumentRealtimes.get(i).getDocumentSize();
				dataForDataTable[i][3] = listDocumentRealtimes.get(i).getModifiedDate();
				dataForDataTable[i][4] = listDocumentRealtimes.get(i).getSharePlace();
				dataForDataTable[i][5] = listDocumentRealtimes.get(i).getDocumentType();
				dataForDataTable[i][6] = listDocumentRealtimes.get(i).getDocumentUrl();
				dataForDataTable[i][7] = listDocumentRealtimes.get(i).getDocumentId();
			}
			render ([info:listDocuments, data:dataForDataTable] as JSON)
		} 
	}
	
	private List<Document> parseListDocumentFromJson(String listDocuments){
		def listObject = JSON.parse(listDocuments);
		List<Document> listDocumentParser = new ArrayList<Document>();
		Document document = null;
		for(int i = 0; i < listObject.size(); i++){
			document = new Document();
			DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
			document.setDocumentId(listObject.get(i).documentId);
            document.setDocumentInTrash(listObject.get(i).documentInTrash);
            document.setModifiedUserId(listObject.get(i).modifiedUserId);
            document.setFileBackup(listObject.get(i).fileBackup);
            document.setSharedFolder(listObject.get(i).sharedFolder);
            document.setDocumentCapacity(listObject.get(i).documentCapacity);
            document.setDocumentType(listObject.get(i).documentType);
            document.setDocumentPermision(listObject.get(i).documentPermission);
            document.setDocumentName(listObject.get(i).documentName);
            document.setDocumentPath(listObject.get(i).documentPath);
            document.setCreateDate(formatter.parse(listObject.get(i).createDate));
            document.setModifiedDate(formatter.parse(listObject.get(i).modifiedDate));
            document.setUserEmail(listObject.get(i).userEmail);
            document.setDocumentUrl(listObject.get(i).documentUrl);
			listDocumentParser.add(document);
		}
		return listDocumentParser;
	}
	
	private boolean compareDocument(Document document1, Document document2){
		boolean compare = true;
		if (compare) compare = document1.getDocumentId().equals(document2.getDocumentId());
		if (compare) compare = document1.isDocumentInTrash() == document2.isDocumentInTrash();
		if (compare) compare = document1.getModifiedUserId().equals(document2.getModifiedUserId());
		if (compare) compare = document1.isFileBackup() == document2.isFileBackup();
		if (compare) compare = document1.isSharedFolder() == document2.isSharedFolder();
		if (compare) compare = document1.getDocumentCapacity().equals(document2.getDocumentCapacity());
		if (compare) compare = document1.getDocumentType().equals(document2.getDocumentType());
		if (compare) compare = document1.getDocumentName().equals(document2.getDocumentName());
		if (compare) compare = document1.getDocumentPath().equals(document2.getDocumentPath());
		if (compare) compare = document1.getCreateDate().compareTo(document2.getCreateDate());
		if (compare) compare = document1.getModifiedDate().compareTo(document2.getModifiedDate());
		if (compare) compare = document1.getDocumentUrl().equals(document2.getDocumentUrl());
		return compare;
	}
	
	private List<DocumentRealtime> convertDocumentToDocumentRealtime(List<Document> listDocuments){
		List<DocumentRealtime> listDocumentRealtime = new ArrayList<DocumentRealtime>();
		List<String> listDocumentString = getListDocumentCapacityString(listDocuments);
		List<String> listDocumentExtension = getListDocumentExtension(listDocuments);
		DocumentRealtime documentRealtime;
		StringBuilder stringBuilder;
		for (int i = 0; i < listDocuments.size(); i++) {
			documentRealtime = new DocumentRealtime();
			stringBuilder = new StringBuilder();
			if (listDocuments.get(i).getDocumentType() == 0){
				stringBuilder.append('<a href="/manage/index?path=');
				if (listDocuments.get(i).getDocumentPath() == null || listDocuments.get(i).getDocumentPath().isEmpty()){
					stringBuilder.append(listDocuments.get(i).getDocumentName());
				}
				else{
					stringBuilder.append(listDocuments.get(i).getDocumentPath() + '/' + listDocuments.get(i).getDocumentName());
				}
				stringBuilder.append('"><img src="/assets/iconManage/');
				if (listDocuments.get(i).isSharedFolder() == true){
					stringBuilder.append("Share_Folder");
				}
				else{
					stringBuilder.append("Folder");
				}
				stringBuilder.append('.png">&nbsp;&nbsp;<span>');
				stringBuilder.append(listDocuments.get(i).getDocumentName());
				stringBuilder.append('</span></a>');
				documentRealtime.setDocumentName(stringBuilder.toString());
				documentRealtime.setDocumentSize('--');
			}
			else{
				stringBuilder.append('<a href="#"><img src="/assets/iconManage/');
				stringBuilder.append(listDocumentExtension.get(i).replaceAll('\\s','_'));
				stringBuilder.append('.png">&nbsp;&nbsp;<span>');
				stringBuilder.append(listDocuments.get(i).getDocumentName());
				stringBuilder.append('</span></a>');
				documentRealtime.setDocumentName(stringBuilder.toString());
				documentRealtime.setDocumentSize(listDocumentString.get(i));
			}
			documentRealtime.setDocumentKind(listDocumentExtension.get(i));
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			documentRealtime.setModifiedDate(df.format(listDocuments.get(i).getModifiedDate()));
			documentRealtime.setSharePlace('<button class="btn-share-on-tr btn btn-success hidden-share" onclick="shareDocument(\'' + listDocuments.get(i).getDocumentType() + '$' + listDocuments.get(i).getDocumentUrl() + '$' + listDocuments.get(i).getDocumentName() + '\')"><i class="fa fa-share"></i> <span>Share</span></button>');
			documentRealtime.setDocumentType(String.valueOf(listDocuments.get(i).getDocumentType()));
			documentRealtime.setDocumentUrl(listDocuments.get(i).getDocumentUrl());
			documentRealtime.setDocumentId(String.valueOf(listDocuments.get(i).getDocumentId()));
			listDocumentRealtime.add(documentRealtime);
		}
		return listDocumentRealtime;
	}
	
	def renameDocument(){
		String documentName = params.documentName;
		Integer documentType = Integer.parseInt(params.documentType);
		Long documentId = Long.parseLong(params.documentId);
		String documentOldName = params.documentOldName;
		String documentPath = params.documentPath;
		String documentEmail = params.documentEmail;
		
		println documentName + " - " + documentType + " - " + documentId + " - " + documentOldName + " - " + documentPath;
		PathDTO pathDTO = new PathDTO();
		pathDTO.setDocumentId(documentId);
		pathDTO.setDocumentType(documentType);
		pathDTO.setNewDocumentName(documentName);
		pathDTO.setNewDocumentPath(documentPath);
		pathDTO.setOldDocumentName(documentOldName);
		pathDTO.setOldDocumentPath(documentPath);
		pathDTO.setPlatform("WEB");
		pathDTO.setUserEmail(documentEmail);
		pathDTO.setMacAddress("");
		Message message;
		RestTemplate restTemplate = new RestTemplate();
		if (documentType == Constant.DOC_FOLDER){
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.RENAME_FOLDER, pathDTO, Message.class);
		}
		else{
			message = restTemplate.postForObject(Constant.SERVICE_URL + ServiceRequest.RENAME_FILE, pathDTO, Message.class);
		}
		println message.response;
		render([info:message.response] as JSON)
	}
	
}
